import { MciCheckbox, MciForm, MciFormItem, MciSelect } from '@/components/base';
import { IGetTableFieldsReq, IGetTableFieldsRes, IGetTableListRes, getTableFields, getTableList } from '@/api';
import { IOption } from '@/components/base/Select';
import { IConditions, IDataLoadForm } from './type';
import { Conditions } from '@/components/business/Conditions';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useDictStore } from '@/store/dict';
import { PropType } from 'vue';
import { CheckboxValueType } from 'element-plus';
import { EOperator } from '@/components/business/Conditions/type';
import { useFormMode } from '@/components/base/Form/mode';

export const DataSet = defineComponent({
  name: 'DataSet',
  props: {
    dataSetData: {
      type: Object as PropType<IDataLoadForm>,
      default: () => ({})
    }
  },
  emits: ['valid'],
  setup(props, { emit, expose }) {
    const formMode = useFormMode();
    // 当前节点
    const currentNode = useCurrentNode();
    const dictStore = useDictStore();
    // 表单
    const dataFormRef = ref<any>();
    const dataForm = reactive<IDataLoadForm>({
      tableName: props.dataSetData?.tableName || '',
      columns: props.dataSetData?.columns || [],
      colnumNames: props.dataSetData?.colnumNames || [],
      conditions: props.dataSetData?.conditions
        ? JSON.parse(JSON.stringify(props.dataSetData?.conditions))
        : {
            conditions: [],
            conjs: [],
            splitIndexes: []
          }
    });
    // 表选项
    const tableOptions = ref<IOption[]>([]);
    // 列选项
    const columnOptions = ref<IOption[]>([]);
    // 多选
    const checkAll = ref(false);
    // 表
    const tableRequest = async () => {
      const data: IGetTableListRes = await getTableList();
      if (data) {
        tableOptions.value = data.map((item: string) => {
          return {
            label: item,
            value: item
          };
        });
      } else {
        tableOptions.value = [];
      }
    };
    tableRequest();

    // 获取数据表的列
    const columnRequest = async () => {
      if (!dataForm.tableName) return;
      const params: IGetTableFieldsReq = {
        tableName: dataForm.tableName
      };
      const data: IGetTableFieldsRes = await getTableFields(params);
      if (data) {
        columnOptions.value = data.map((item: any) => {
          return {
            label: item.varLabel ? item.varLabel : item.varName,
            value: item.varName
          };
        });
        dataForm.colnumNames = columnOptions.value.map((item: any) => {
          return item.label;
        });
      } else {
        columnOptions.value = [];
        dataForm.colnumNames = [];
      }
    };

    if (dataForm.tableName) {
      columnRequest();
    }

    // 表单校验-表名
    const tableNameValidator = (rule: any, value: string, callback: any) => {
      if (!dataForm.tableName) {
        return callback(new Error('请选择数据集'));
      }
      callback();
    };

    // 表单校验-条件
    const conditionsValidator = (rule: any, value: string, callback: any) => {
      if (!dataForm.conditions) {
        return callback(new Error('请添加条件'));
      }
      if (!dataForm.conditions.conditions || !dataForm.conditions.conditions.length) {
        return callback(new Error('请添加条件'));
      }
      dataForm.conditions.conditions.forEach((element: any, index: number) => {
        if (element) {
          if (!element.left) {
            const desc = `第${index + 1}个条件的左操作数不可为空`;
            return callback(new Error(desc));
          }
          if (!element.operator) {
            const desc = `第${index + 1}个条件的运算符不可为空`;
            return callback(new Error(desc));
          }
          if (!element.rightType && element.operator !== EOperator.IsEmpty && element.operator !== EOperator.IsNotEmpty) {
            const desc = `第${index + 1}个条件的值来源不可为空`;
            return callback(new Error(desc));
          }
          if (
            !element.right &&
            element.right !== 0 &&
            element.right !== false &&
            element.operator !== EOperator.IsEmpty &&
            element.operator !== EOperator.IsNotEmpty
          ) {
            const desc = `第${index + 1}个条件的值不可为空`;
            return callback(new Error(desc));
          }
        }
      });
      callback();
    };

    const rules = reactive<any>({
      tableName: [{ required: formMode?.mode === 'edit' ? true : false, message: '请选择数据集', validator: tableNameValidator }],
      conditions: [{ required: formMode?.mode === 'edit' ? true : false, message: '请添加条件', validator: conditionsValidator }]
    });

    // 表单校验
    const formValidate = () => {
      dataFormRef.value?.validate((valid: any) => {
        if (valid) {
          emit('valid', dataForm);
        }
      });
    };

    watch(
      [() => dataForm.tableName],
      () => {
        columnRequest();
      },
      { deep: true }
    );
    watch(
      [() => props.dataSetData],
      () => {
        dataForm.tableName = props.dataSetData?.tableName || '';
        dataForm.columns = props.dataSetData?.columns || [];
        dataForm.colnumNames = props.dataSetData?.colnumNames || [];
        dataForm.conditions = props.dataSetData?.conditions
          ? JSON.parse(JSON.stringify(props.dataSetData?.conditions))
          : {
              conditions: [],
              conjs: [],
              splitIndexes: []
            };
      },
      { deep: true }
    );

    expose({
      formValidate
    });

    return () => {
      const variableOptions = currentNode.currentAndParentPrivateVariablesOptions.value.concat(
        currentNode.currentAndParentNodeVariablesOptions.value
      );
      const variableOptionsWithSystem = dictStore.systemVarsOptions.concat(variableOptions);
      return (
        <div class="w-full">
          <MciForm ref={dataFormRef} data={dataForm} rules={rules} label-width={'auto'} label-position={'top'}>
            <MciFormItem label="数据集" prop="tableName" class="w-full">
              <MciSelect
                vModel={dataForm.tableName}
                list={tableOptions.value}
                style={{ width: 'calc(100% - 8px)' }}
                size="default"
              />
            </MciFormItem>
            <MciFormItem label="查询列" prop="columns" class="w-full flex justify-end">
              {formMode?.mode === 'edit' ? (
                <MciSelect
                  vModel={dataForm.columns}
                  list={columnOptions.value}
                  multiple={true}
                  class="w-full"
                  collapse-tags={true}
                  max-collapse-tags={1}
                  collapse-tags-tooltip>
                  {{
                    header: () => {
                      return (
                        <MciCheckbox
                          vModel={checkAll.value}
                          onChange={(val: CheckboxValueType) => {
                            if (val) {
                              dataForm.columns = columnOptions.value.map((_: IOption) => _.value) as string[];
                              dataForm.colnumNames = columnOptions.value.map((_: IOption) => _.label) as string[];
                            } else {
                              dataForm.columns = [];
                              dataForm.colnumNames = [];
                            }
                          }}>
                          全选
                        </MciCheckbox>
                      );
                    }
                  }}
                </MciSelect>
              ) : (
                <div>
                  <div>{dataForm.colnumNames ? dataForm.colnumNames.join('，') : ''}</div>
                </div>
              )}
            </MciFormItem>
            <MciFormItem label="条件" prop="conditions">
              <Conditions
                modelValue={dataForm.conditions}
                onUpdate:modelValue={(val: IConditions) => {
                  dataForm.conditions = val;
                }}
                class="flex-1"
                variableOptions={variableOptionsWithSystem}
                leftOptions={columnOptions.value}
              />
            </MciFormItem>
          </MciForm>
        </div>
      );
    };
  }
});
